/**
 * Axios网络拦截器
 * 自动将所有axios请求记录到调试面板
 */

import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';

interface RequestTiming {
  [key: string]: {
    startTime: number;
    config: AxiosRequestConfig;
  };
}

class AxiosDebugInterceptor {
  private requestTimings: RequestTiming = {};
  private requestIdCounter = 0;

  /**
   * 生成唯一请求ID
   */
  private generateRequestId(): string {
    return `axios_${Date.now()}_${++this.requestIdCounter}`;
  }

  /**
   * 安装拦截器
   */
  install() {
    // 请求拦截器
    axios.interceptors.request.use(
      (config) => {
        const requestId = this.generateRequestId();
        const startTime = Date.now();
        
        // 在config中保存请求ID，用于响应时匹配
        config.metadata = { requestId, startTime };
        
        // 保存请求时间信息
        this.requestTimings[requestId] = {
          startTime,
          config: { ...config }
        };

        // 记录请求开始
        if (global.$debug) {
          global.$debug.info(`🌐 HTTP请求开始: ${config.method?.toUpperCase()} ${config.url}`, {
            requestId,
            method: config.method?.toUpperCase(),
            url: config.url,
            baseURL: config.baseURL,
            headers: this.sanitizeHeaders(config.headers),
            params: config.params,
            data: this.sanitizeRequestData(config.data),
            timeout: config.timeout,
            timestamp: new Date().toISOString()
          });
        }

        return config;
      },
      (error: AxiosError) => {
        // 请求配置错误
        if (global.$debug) {
          global.$debug.errorLog(error, 'Axios请求配置错误');
        }
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    axios.interceptors.response.use(
      (response: AxiosResponse) => {
        const requestId = response.config.metadata?.requestId;
        const startTime = response.config.metadata?.startTime;
        const duration = startTime ? Date.now() - startTime : 0;

        // 清理请求时间记录
        if (requestId && this.requestTimings[requestId]) {
          delete this.requestTimings[requestId];
        }

        // 记录成功响应
        if (global.$debug) {
          global.$debug.info(`✅ HTTP请求成功: ${response.config.method?.toUpperCase()} ${response.config.url} (${duration}ms)`, {
            requestId,
            method: response.config.method?.toUpperCase(),
            url: response.config.url,
            status: response.status,
            statusText: response.statusText,
            headers: this.sanitizeHeaders(response.headers),
            data: this.sanitizeResponseData(response.data),
            duration,
            timestamp: new Date().toISOString()
          });

          // 记录到网络日志
          global.$debug.networkLog(
            response.config.method?.toUpperCase() || 'GET',
            response.config.url || '',
            this.sanitizeRequestData(response.config.data),
            this.sanitizeResponseData(response.data),
            duration
          );
        }

        return response;
      },
      (error: AxiosError) => {
        const requestId = error.config?.metadata?.requestId;
        const startTime = error.config?.metadata?.startTime;
        const duration = startTime ? Date.now() - startTime : 0;

        // 清理请求时间记录
        if (requestId && this.requestTimings[requestId]) {
          delete this.requestTimings[requestId];
        }

        // 记录错误响应
        if (global.$debug) {
          const statusCode = error.response?.status;
          const isNetworkError = !error.response;
          
          global.$debug.error(`❌ HTTP请求失败: ${error.config?.method?.toUpperCase()} ${error.config?.url} (${duration}ms)`, {
            requestId,
            method: error.config?.method?.toUpperCase(),
            url: error.config?.url,
            error: error.message,
            code: error.code,
            status: statusCode,
            statusText: error.response?.statusText,
            isNetworkError,
            responseHeaders: error.response ? this.sanitizeHeaders(error.response.headers) : null,
            responseData: error.response ? this.sanitizeResponseData(error.response.data) : null,
            duration,
            timestamp: new Date().toISOString()
          });

          // 记录到网络日志（包含错误信息）
          global.$debug.networkLog(
            error.config?.method?.toUpperCase() || 'GET',
            error.config?.url || '',
            this.sanitizeRequestData(error.config?.data),
            {
              error: error.message,
              status: statusCode,
              data: error.response?.data
            },
            duration
          );
        }

        return Promise.reject(error);
      }
    );

    console.log('🔧 Axios调试拦截器已安装');
  }

  /**
   * 清理敏感请求头信息
   */
  private sanitizeHeaders(headers: any): any {
    if (!headers) return headers;
    
    const sensitiveHeaders = ['authorization', 'cookie', 'x-api-key', 'x-auth-token'];
    const sanitized = { ...headers };
    
    Object.keys(sanitized).forEach(key => {
      if (sensitiveHeaders.includes(key.toLowerCase())) {
        sanitized[key] = '***HIDDEN***';
      }
    });
    
    return sanitized;
  }

  /**
   * 清理请求数据（隐藏敏感信息）
   */
  private sanitizeRequestData(data: any): any {
    if (!data) return data;
    
    // 如果是字符串，尝试解析为JSON
    if (typeof data === 'string') {
      try {
        data = JSON.parse(data);
      } catch {
        return data; // 无法解析，直接返回
      }
    }
    
    if (typeof data === 'object') {
      const sensitiveFields = ['password', 'token', 'secret', 'key', 'auth'];
      const sanitized = { ...data };
      
      Object.keys(sanitized).forEach(key => {
        if (sensitiveFields.some(field => key.toLowerCase().includes(field))) {
          sanitized[key] = '***HIDDEN***';
        }
      });
      
      return sanitized;
    }
    
    return data;
  }

  /**
   * 清理响应数据（限制大小，隐藏敏感信息）
   */
  private sanitizeResponseData(data: any): any {
    if (!data) return data;
    
    // 限制响应数据大小，避免调试面板卡顿
    const dataString = JSON.stringify(data);
    if (dataString.length > 10000) {
      return {
        _truncated: true,
        _originalSize: dataString.length,
        _preview: dataString.substring(0, 1000) + '... (truncated)',
        _message: '响应数据过大，已截断显示'
      };
    }
    
    return data;
  }

  /**
   * 获取拦截器统计信息
   */
  getStats() {
    return {
      pendingRequests: Object.keys(this.requestTimings).length,
      totalIntercepted: this.requestIdCounter
    };
  }
}

// 全局扩展AxiosRequestConfig类型
declare module 'axios' {
  interface AxiosRequestConfig {
    metadata?: {
      requestId: string;
      startTime: number;
    };
  }
}

// 创建并导出拦截器实例
const axiosInterceptor = new AxiosDebugInterceptor();

export default axiosInterceptor;

